import React from 'react';
import {Alert, Image, Platform, StatusBar, StyleSheet, View,} from 'react-native';
import * as Color from "../../../lib.xjs/constant/Color";
import HttpHelper from "../../../lib.xjs/helper/HttpHelper";
import * as BizConstant from "../../constant/BizContant";
import {UUID} from "../../../lib.xjs/util/UUID";
import L from "../../../lib.xjs/util/L";
import BizUser from "../../entity/BizUser";
import StorageUtil from "../../../lib.xjs/util/StorageUtil";
import ToastAndroid from "react-native/Libraries/Components/ToastAndroid/ToastAndroid.android";
import OpacityButton from "../../../lib.xjs/widget/btn/OpacityButton";
import {NavigationActions} from 'react-navigation';

import {isFirstTime, isRolledBack, markSuccess,} from 'react-native-update';

import _updateConfig from "../../../../update";
import VersionCheckHelper from "../../helper/VersionCheckHelper";

const {appKey} = _updateConfig[Platform.OS];

/** 登录 */
export default class BizAppStartUp extends React.Component {

    /** 首页等待时长(毫秒) */
    static DELAY_ALL:number = 3000;
    timer = null;
    /** 是否可以跳过 */
    isCanSkip:boolean = false;
    /** 是否存在历史数据 */
    isHistoryInfoExist:boolean = false;
    /** 当存在历史数据时, 是否等待网络加载个人信息 */
    isWaitPersonInfo:boolean = true;
    /** 是否可以进入主页面 */
    isCanGoMain:boolean = true;

    /** 检测新版本 */
    mVersionCheckHelper:VersionCheckHelper;

    /**
     * 是否取消等待(跳过)
     * 1.没有历史数据->去登录
     * 2.有历史数据,正在自动登录(获取相关数据)->去登录
     * 3.有历史数据,以获取相关数据完成->去主界面
     */
    static navigationOptions = ({navigation}) => ({
        title: '登录',
        // header: null,
    });

    constructor(props){
        super(props);
        this.state=({
            textBtn: '3秒',
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    hidden={true}
                    translucent={true}
                    backgroundColor={Color.colorPrimaryDark}/>

                <View style={styles.line_1}>
                    <OpacityButton
                        disabled={false}
                        title={this.state.textBtn}
                        style={styles.btnTimer}
                        onPress={()=> this._doOnSkipBtnClick()}/>
                </View>

                <Image source={require('../../../../img/gaqu/ic_startup_logo.png')}
                       style={styles.titleImage}
                       resizeMode={Image.resizeMode.contain}/>

                <Image source={require('../../../../img/gaqu/ic_startup_fg.png')}
                       style={styles.backgroundImage}
                       resizeMode={Image.resizeMode.contain}/>
                <HttpHelper ref={'http'}/>
            </View>
        );
    }

    /** 将要挂载 */
    componentWillMount() {
        if (isFirstTime) {
            markSuccess();
        } else if (isRolledBack) {
            Alert.alert('提示', '刚刚更新失败了,版本被回滚.');
        }
    }

    /** 已经挂载 */
    componentDidMount(): void {
        this.mVersionCheckHelper = new VersionCheckHelper();
        this.mVersionCheckHelper.checkUpdate(this._onCheckVersionBack);

        this._doCheckHistory();
        this._doStartTik();
    }

    /** 将要卸载 */
    componentWillUnmount(): void {
        // 如果存在this.timer，则使用clearTimeout清空。
        this.timer && clearInterval(this.timer);
        this.isCanSkip = false;
        this.isHistoryInfoExist = false;
        this.isWaitPersonInfo = true;
    }

    /** 检测是否存在历史信息 */
    _doCheckHistory(){
        let token = "";
        let mobile = "";

        StorageUtil.getInstance().doLoad("history", null, null, (ret) => {
            if(!ret){
                ToastAndroid.show('没有历史记录', ToastAndroid.SHORT);
                L.logOnly("没有历史记录");
                this.isCanSkip = true;
                return;
            }

            token = BizUser.token = ret.token;  // -----------------------------------------------
            mobile = ret.mobile;
            this.isHistoryInfoExist = token && mobile;

            if (!this.isHistoryInfoExist) {
                ToastAndroid.show('没有历史记录', ToastAndroid.SHORT);
                this.isCanSkip = true;
                return;
            }
            this._doLoadPersonInfo();
        });
    }

    /** 当有历史数据存在时,直接拉取个人信息 */
    _doLoadPersonInfo(){
        if (!this.refs.http) return;
        let head = BizUser.getHeadParam(true);

        this.refs.http.setURL(BizConstant.GET_ROLE)
            .setMethod(HttpHelper.GET)
            .setNotiInfo("正在查询")
            .setHeadParams(head)
            .setBodyParams(new Map())
            .setRequestId(UUID.getOne())
            .setListener((responseCode: number, res: Object) => {
                if(!this.isWaitPersonInfo) return;  // 都不等待我这个查询结果了
                this.isCanSkip = true;
                if (responseCode !== HttpHelper.RESPONSE_SUCCESS) {
                    this.isHistoryInfoExist = false;
                    // StorageUtil.getInstance().doSave("history", "");
                    // 免登陆失败,跳转登录
                    return;
                }

                // 初始化全局变量
                let bizUser     = {};
                bizUser.token   = BizUser.token;
                bizUser.roles   = res.data.roles;
                global.bizUser  = bizUser;
            })
            .setTimeout(10 * 1000)
            .start(true);
    }


    /** 开始计时 */
    _doStartTik() {
        this.tempDelay = BizAppStartUp.DELAY_ALL;
        this.timer = setInterval(
            ()=>{
                this.tempDelay -= 500;
                if((this.tempDelay % 1000) === 0) this._doOnReachedSecond(this.tempDelay);
            },
            500,
        );
    }

    /** 当计时到每秒 */
    _doOnReachedSecond(tempDelay:number){
        let infoSkip = (this.isCanSkip ? "跳过" : "");
        let infoTime = "";
        if(this.isCanSkip) infoTime = "(" + (tempDelay/1000) + "秒)";
        else infoTime = (tempDelay/1000) + "秒";

        let info = infoSkip + infoTime;
        // 显示出来
        this.setState({
            textBtn: info,
        });
        if(tempDelay <= 0) {
            this._doOnTimeOut();
            if(this.timer) clearInterval(this.timer);
        }
    }

    /** 时间到了 */
    _doOnTimeOut(){
        L.logOnly("时间到了");
        if(!this.isCanGoMain) return;
        // 没有历史数据
        // 1. 直接跳转登录
        if(!this.isHistoryInfoExist){
            this._doLogin();
            return;
        }

        // 有历史数据
        // 2. 等待网络自行加载完成
        if(global.bizUser){     // 网络加载完成
            L.logOnly("有历史数据,网络加载成功");
            this._gotoRoleSelect();
        }
        else{                   // 网络加载还没有完成
            L.logOnly("有历史数据,网络加载失败,或来不及");
            this.isWaitPersonInfo = false;  // 那我们就不等它的结果了, 自己来
            this._doLogin();
        }
    }

    /** 点击跳过按钮 */
    _doOnSkipBtnClick(){
        L.logOnly("_doOnSkipBtnClick");
        if(!this.isCanGoMain) return;
        if(!this.isCanSkip) return;
        // 没有历史数据
        // 1. 直接跳转登录
        if(!this.isHistoryInfoExist){
            this._doLogin();
            return;
        }

        // 有历史数据
        // 2. 是否网络加载已经完成(global.bizUser存在)
        // 2.1 是:则直接跳转主页面
        // 2.2 否:将等待网络结果置否, 直接跳转登录页
        if(global.bizUser){
            this._gotoRoleSelect();
        }
        else{
            this.isWaitPersonInfo = false;
        }
    }

    /** 去登陆 */
    _doLogin(): void {
        L.logOnly("去登陆");
        // 清空栈跳转
        let resetAction = NavigationActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({routeName:'GaQuLogin'}) // 要跳转到的页面名字
            ]
        });
        this.props.navigation.dispatch(resetAction);
    }

    /** 去选择角色 */
    _gotoRoleSelect(): void{
        // 清空栈跳转
        let resetAction = NavigationActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({routeName:'RoleSelect'}) // 要跳转到的页面名字
            ]
        });
        this.props.navigation.dispatch(resetAction);
    }

    /**
     * 新版本检测
     * @param isCanGoMain 是否可以进入主页面
     * @private
     */
    _onCheckVersionBack = (isCanGoMain: boolean) => {
        this.isCanGoMain = isCanGoMain;
    }
}

const styles = StyleSheet.create({
    container: {
        flex:1,
        flexDirection: 'column',
        alignItems: 'center',
        paddingLeft: 25,
        paddingRight: 25,
        paddingTop: 25,
        backgroundColor: Color.white,
    },
    line_1: {
        width: "100%",
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center',
    },
    btnTimer: {
        width: 20,
        height: 10,
        alignSelf: 'flex-end',
    },
    titleImage: {
        width: 200,
        height: 100,
        marginTop:50,
    },
    backgroundImage: {
        width: 250,
        height: 250,
        marginTop:25,
    },
});


